﻿using AutoMapper;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using NewLife.Redis.Core;
using Newtonsoft.Json;
using Qiniu.Http;
using Qiniu.Storage;
using Qiniu.Util;
using System;
using System.Collections.Generic;
using System.DirectoryServices.Protocols;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WomanMotion.WebApi.Infrastructure.UnifyResult;
using WomanMotion.WebApi.Infrastructure.YitId;
using WomanMotion.WebApi.Model.Common.FileUpload;
using WomanMotion.WebApi.Model.Dtos.Controller;
using WomanMotion.WebApi.Service.IService;

namespace WomanMotion.WebApi.Service.Service
{
    /// <summary>
    /// 公共服务
    /// </summary>
    public class CommonService : BaseService, ICommonService
    {
        private readonly INewLifeRedis _redis;
        private readonly IActionsService _actions;
        private readonly IControllerService _controller;
        private readonly IConfiguration _configuration;

        public CommonService(ILogger<CommonService> logger, IMapper mapper, INewLifeRedis redis, IActionsService actions, IControllerService controller, IConfiguration configuration) : base(logger, mapper)
        {
            this._redis = redis;
            _actions = actions;
            _controller = controller;
            _configuration = configuration;
        }

        ///// <summary>
        ///// 文件上传接口上传本地
        ///// </summary>
        ///// <param name="file"></param>
        ///// <returns></returns>
        //public async Task<FileInfoVM> FileUpload(IFormFile file)
        //{
        //    FileUploadA(file);
        //    string fileExtension = Path.GetExtension(file.FileName).ToLower();
        //    var path = AppDomain.CurrentDomain.BaseDirectory;
        //    //获取文件后缀名
        //    var year = DateTime.Now.Year.ToString().Substring(2, 2);
        //    var month = DateTime.Now.Month.ToString().PadLeft(2, '0');
        //    var day = DateTime.Now.Day.ToString().PadLeft(2, '0');
        //    var strdate = year + month + day;
        //    var sevepath = path + @"wwwroot/UploadFile/" + strdate + @"/";

        //    if (!Directory.Exists(sevepath))//如果路径不存在
        //    {
        //        Directory.CreateDirectory(sevepath);//创建一个路径的文件夹
        //    }
        //    var filename = YitIdHelper.NextId().ToString() + fileExtension;
        //    try
        //    {
        //        using (FileStream fs = System.IO.File.Create(sevepath + filename))
        //        {
        //            await file.CopyToAsync(fs);
        //            fs.Flush();
        //        }
        //        var filevm = new FileInfoVM();
        //        filevm.filename = file.FileName;
        //        filevm.filepath = @"UploadFile/" + strdate + @"/" + filename;
        //        return filevm;
        //    }
        //    catch (Exception ex)
        //    {
        //        return null;
        //    }
        //}

        /// <summary>
        /// 文件上传接口上传七牛
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public FileInfoVM FileUpload(IFormFile file)
        {
            //获取文件后缀名
            string fileExtension = Path.GetExtension(file.FileName).ToLower();
            //获取当前年月日
            var year = DateTime.Now.Year.ToString().Substring(2, 2);
            var month = DateTime.Now.Month.ToString().PadLeft(2, '0');
            var day = DateTime.Now.Day.ToString().PadLeft(2, '0');
            var strdate = year + month + day;
            //文件名等于雪花id加后缀
            var filename = YitIdHelper.NextId().ToString() + fileExtension;
            //完整文件名等于日期文件夹加文件名
            var filefullname = strdate + @"/" + filename;
            //获取七牛配置文件
            var qiuniuconfigMoble = _configuration.GetSection("Qiniu").Get<QiNiuConfigModel>();
            FormUploader upload = new FormUploader(new Config()
            {
                Zone = Zone.ZONE_CN_South,//华南
                UseHttps = true //是否使用https
            });
            //获取token
            Mac mac = new Mac(qiuniuconfigMoble.AK, qiuniuconfigMoble.SK);
            PutPolicy putPolicy = new PutPolicy { Scope = qiuniuconfigMoble.Bucket };
            var qiniutoken = Auth.CreateUploadToken(mac, putPolicy.ToJsonString());
            using (Stream stream = file.OpenReadStream())
            {
                HttpResult result = upload.UploadStream(stream, filefullname, qiniutoken, null);
                if (result.Code == 200)
                {
                    var resulttest = JsonConvert.DeserializeObject<QiNiuTextResult>(result.Text);
                    var filevm = new FileInfoVM();
                    filevm.filename = file.FileName;
                    filevm.filepath = qiuniuconfigMoble.Host + "/" + resulttest.key;
                    return filevm;
                }
                else
                {
                    return null;
                }
            }
        }
    }
}